<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="postForm"
      label-position="right"
      label-width="100px"
      style="width: 600px; margin-left:50px;"
    >
      <el-form-item label="资源名称" prop="resourceName">
        <el-input v-model="postForm.resourceName" clearable placeholder="请输入资源名称" maxlength="20" />
      </el-form-item>
      <el-form-item hidden>
        <el-input id="parentId" v-model="postForm.parentId" readonly hidden />
      </el-form-item>
      <el-form-item label="上级节点" prop="parentName">
        <el-input
          id="parentName"
          v-model="postForm.parentName"
          readonly
          placeholder="请选择上级节点"
          style="width:55%;float:left; margin-right: 10px;"
        />
        <el-button v-waves type="warning" icon="el-icon-search" @click="selectResource">
          选择
        </el-button>
      </el-form-item>
      <el-form-item label="资源类别" prop="resourceType">
        <el-select v-model="postForm.resourceType" placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in resourceTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资源路径" prop="url">
        <el-input v-model="postForm.url" clearable placeholder="请输入资源路径" maxlength="100" />
      </el-form-item>
      <el-form-item label="权限代码" prop="resourceCode">
        <el-input v-model="postForm.resourceCode" clearable placeholder="请输入权限代码" maxlength="40" />
      </el-form-item>
      <el-form-item label="排序号" prop="displayOrder">
        <el-input-number v-model="postForm.displayOrder" clearable placeholder="请输入排序号" maxlength="20" />
      </el-form-item>
      <el-form-item label="目标" prop="target">
        <el-input v-model="postForm.target" clearable placeholder="请输入资源目标" maxlength="30" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="postForm.status" placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in statusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <div style="height: 32px;">
        <label style="font-size: 15px; font-weight: normal">路由信息</label>
      </div>-->
      <!--<el-form-item label="路由组件" prop="component">
        <el-input v-model="postForm.component" clearable placeholder="请输入路由组件" maxlength="200" />
      </el-form-item>-->
      <!-- <el-form-item label="路由地址" prop="path">
        <el-input v-model="postForm.path" clearable placeholder="请输入路由地址" maxlength="100" />
      </el-form-item>-->
      <el-form-item label="菜单图标" prop="icon">
        <el-input v-model="postForm.icon" clearable placeholder="请输入资源图标" maxlength="128" />
      </el-form-item>
      <el-form-item label="是否显示" prop="isShow">
        <el-select v-model="postForm.isShow" placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in showsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="资源描述" prop="resourceDesc">
        <textarea
          v-model="postForm.resourceDesc"
          clearable
          placeholder="请输入资源描述"
          style="height: 80px"
          class="el-input__inner"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-waves @click="back">返回</el-button>
        <el-button v-waves type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
    <!--弹出框选择上级节点 -->
    <el-dialog :visible.sync="dialogVisible" width="550px" title="选择上级资源">
      <el-form label-width="50px" label-position="left">
        <el-form-item label="资源">
          <el-input v-model="filterText" placeholder="输入资源名称查询" />
          <el-tree
            ref="tree"
            class="filter-tree"
            :data="resourceData"
            :props="defaultProps"
            highlight-current
            default-expand-all
            :filter-node-method="filterNode"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSelect">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addSysResource,
  updateSysResource,
  getSysResource,
  getSysResourceTree,
  checkResourceCode
} from '@/api/sys/resource'
import waves from '@/directive/waves'
import msgUtil from '@/utils/msgUtil'
import routerUtil from '@/utils/routerUtil'

const defaultForm = {
  id: null,
  resourceName: null,
  parentId: 0,
  parentName: null,
  resourceType: 0,
  displayOrder: 1,
  url: null,
  target: null,
  icon: null,
  isShow: 0,
  resourceCode: null,
  status: 0,
  resourceDesc: null,
  keepAlive: 0,
  component: null,
  path: null,
  authSystemId: null
  // createdBy: getUserId()
}

// 资源状态
const statusOptions = [
  {
    value: 0,
    label: '正常'
  },
  {
    value: 1,
    label: '禁用'
  }
]
// 是否显示
const showsOptions = [
  {
    value: 0,
    label: '显示'
  },
  {
    value: 1,
    label: '隐藏'
  }
]
// 资源类别
const resourceTypeOptions = [
  {
    value: 0,
    label: '模块'
  },
  {
    value: 1,
    label: '功能'
  }
]

// 处理返回的资源数据生成资源选择树
export function filterResourceTree(resources) {
  const res = []
  resources.forEach(resource => {
    const tmp = {}
    tmp.id = resource.id
    if (Number(document.getElementById('parentId').value) === Number(resource.id)) {
      document.getElementById('parentName').value = resource.resourceName
    }
    tmp.label = resource.resourceName
    if (resource.resourceType === 0 && resource.children) {
      tmp.children = filterResourceTree(resource.children)
      res.push(tmp)
    }
  })
  return res
}

export default {
  name: 'ResourceDetail',
  directives: { waves },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validResourceCode = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        callback(new Error('权限代码不能为空'))
      } else {
        if (this.oldResourceCode !== value) {
          this.checkResourceCode(value, callback)
        } else {
          callback()
        }
      }
    }
    return {
      loading: true,
      statusOptions,
      showsOptions,
      resourceTypeOptions,
      dialogVisible: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      authSystemId: null,
      oldResourceCode: null,
      systemOptions: [],
      dialogType: 'new',
      pResourceName: null,
      postForm: Object.assign({}, defaultForm),
      rules: {
        resourceName: [
          { required: true, message: '资源名称不能为空', trigger: 'change' }
        ],
        resourceType: [
          { required: true, message: '请选择资源类别', trigger: 'change' }
        ],
        url: [
          { required: true, message: '资源路径不能为空，如无路径请用#代替', trigger: 'change' }
        ],
        resourceCode: [
          { required: true, validator: validResourceCode, trigger: 'change' }
        ]
      },
      filterText: '',
      resourceData: '',
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getResourceTree()
    if (this.isEdit) {
      this.getSysResource(this.$route.query.id)
    } else {
      this.loading = false
    }
    this.getResourceTree()
  },
  methods: {
    showResource() {
      this.getResourceTree()
    },
    /**
       * 获取弹窗resourceTree
       */
    getResourceTree() {
      getSysResourceTree({}).then(response => {
        this.resourceData = filterResourceTree(response.data)
      })
    },
    /**
       * 获取当前sysResource的值
       * @param id
       */
    getSysResource(id) {
      getSysResource({ id: id }).then(response => {
        this.postForm = Object.assign(this.postForm, response.data)
        this.oldResourceCode = response.data.resourceCode
        this.getResourceTree()
        this.loading = false
      })
    },
    // 校验资源代码是否唯一
    checkResourceCode(code, callback) {
      checkResourceCode({ resourceCode: code }).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          callback(new Error(response.msg))
        } else {
          callback()
        }
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    selectResource() {
      this.dialogType = 'new'
      this.dialogVisible = true
      this.closeOnClickModal = false
      this.closeOnPressEscape = false
    },
    back() {
      routerUtil.backPath(this, '/sys/resource/index')
    },
    confirmSelect() {
      this.postForm = Object.assign(this.postForm, {
        parentId: this.$refs.tree.getCurrentNode().id,
        parentName: this.$refs.tree.getCurrentNode().label
      })
      this.dialogVisible = false
    },
    updateSysResource() {
      updateSysResource(this.postForm).then(response => {
        msgUtil.success()
        routerUtil.backPath(this, '/sys/resource/index')
      })
    },
    addSysResource() {
      addSysResource(this.postForm).then(response => {
        msgUtil.success()
        routerUtil.backPath(this, '/sys/resource/index')
      })
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          if (this.isEdit) {
            this.updateSysResource()
          } else {
            this.addSysResource()
          }
        }
      })
    }
  }
}

</script>
<style scoped>

</style>
